import {ScrollView, View, Text, Image, Input, Textarea} from '@tarojs/components';
import React, {Component} from 'react';
import Taro, {getCurrentInstance} from '@tarojs/taro';
import {AtActionSheet} from 'taro-ui';
import 'taro-ui/dist/style/components/action-sheet.scss';
import {connect} from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';
import api from 'api';
import ChooseImageView from '@/pages/common/image-upload/choose-image-view';
import ChooseVideoView from '@/pages/common/video-upload/choose-video-view';
import upImg from '@/assets/image/community/upImg.png';
import check from '@/assets/image/community/c_check.png';
import checked from '@/assets/image/community/c_checked.png';
import close from '@/assets/image/community/close.png';
import right from '@/assets/image/community/right.png';

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      //提交的内容
      subinfor: {
        content: '', //内容
        url: '', //图片url，用;拼接
        publishUser: '', //发布人id
      },
      imgList: [],
      videoList: [],
      showModel: false,
      titleId: null,
      titleName: '',
    };
  }

  componentDidMount() {
    this.props.actions.init();
  }

  componentDidShow() {}

  componentWillUnmount() {}

  onChooseImageChange = (detailFiles) => {
    this.setState(
      {
        detailFiles,
      },
      () => {
        let imgList = [];
        detailFiles.map((item) => {
          imgList.push(item.url);
        });
        this.setState({imgList});
        console.log(this.state.detailFiles);
      },
    );
  };

  onChooseVideoChange = (detailFiles) => {
    this.setState(
      {
        detailFiles,
      },
      () => {
        let videoList = [];
        detailFiles.map((item) => {
          videoList.push(item.url);
        });
        this.setState({videoList});
        console.log(this.state.detailFiles);
      },
    );
  };

  // 提交内容
  async submitPost() {
    const {subinfor, isChecked, imgList, videoList, titleId} = this.state;
    if (subinfor.content.trim() == '') {
      Taro.showToast({
        title: '文本不能为空！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (imgList.length == 0) {
      Taro.showToast({
        title: '图片不能为空！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (titleId == null) {
      Taro.showToast({
        title: '帖子类型不能为空！',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    Taro.showLoading({
      title: '提交中...',
    });
    let userInfo = Taro.getStorageSync('b2b-wechat@login').user;
    let selectDistance = Taro.getStorageSync('selectDistance');
    // 发布范围
    let scopeType;
    if (isChecked == false) {
      scopeType = 0;
    } else {
      scopeType = selectDistance.code;
    }
    let url = '';
    if (imgList.length > 0) {
      url = imgList.join(';');
    }
    var params = {
      publishUser: userInfo.id,
      content: subinfor.content,
      url,
      videoUrl: videoList.length > 0 ? videoList[0].url : '',
      videoImg: videoList.length > 0 ? videoList[0].img : '',
      scope: scopeType,
      titleId,
    };
    let res = await api.forumController.addForum(params);
    Taro.hideLoading();
    if (res.success) {
      Taro.showToast({
        title: '新增成功！',
        icon: 'none',
        duration: 2000,
      });
      Taro.navigateBack();
    } else {
      Taro.showToast({
        title: res.msg,
        icon: 'none',
        duration: 2000,
      });
    }
  }

  render() {
    let {
      main: {tabList},
      actions: {action},
    } = this.props;
    let {subinfor, isChecked, imgList, videoList, showModel, titleId, titleName} = this.state;
    let detailImages = [];
    imgList.map((item) => {
      detailImages.push({url: item});
    });
    let detailVideos = [];
    videoList.map((item) => {
      detailVideos.push({url: item});
    });
    return (
      <ScrollView className="packageBNewPost" scrollY>
        <View className="i_box">
          <Textarea
            placeholderStyle="color:#BFBFBF;"
            className="textarea"
            autoHeight
            maxlength={512}
            placeholder="晒晒你身边趣事，分享美好生活"
            value={subinfor.content ? subinfor.content.substring(0, 512) : ''}
            onInput={(e) => {
              let sss = subinfor;
              sss.content = e.detail.value;
              if (sss.content.length >= 512) {
                sss.content = sss.content.substring(0, 512);
                Taro.showToast({
                  title: '字数已达上限',
                  icon: 'none',
                  duration: 2000,
                });
              }
              this.setState({
                subinfor: sss,
              });
            }}
          />
        </View>
        <View className="length">{subinfor.content.length}/512</View>
        {/* <Text className='uploadLabel'>上传视频</Text>
        <ChooseVideoView files={detailVideos} maxCount="1" onFileChange={this.onChooseVideoChange.bind(this)} /> */}
        <Text className="uploadLabel">上传图片</Text>
        <ChooseImageView files={detailImages} maxCount="5" onFileChange={this.onChooseImageChange.bind(this)} />
        <View className="scopes border">
          <Text className="scopesTitle">发布范围</Text>
          <View
            onClick={() => {
              this.setState({
                isChecked: !isChecked,
              });
            }}
            className="stylesRadio"
          >
            {isChecked == false ? (
              <Image style={{width: '42rpx', height: 'auto'}} src={check} mode="widthFix" />
            ) : (
              <Image style={{width: '42rpx', height: 'auto'}} src={checked} mode="widthFix" />
            )}
            <Text className="stylesRadioText">本小区</Text>
          </View>
        </View>
        <View className="scopes">
          <Text className="scopesTitle">帖子类型</Text>
          <View className="stylesRadio" onClick={() => this.setState({showModel: true})}>
            {titleName ? (
              <Text className="stylesRadioText">{titleName}</Text>
            ) : (
              <Text className="typeText">请选择</Text>
            )}
            <Image style={{width: '16rpx', height: 'auto'}} src={right} mode="widthFix" />
          </View>
        </View>
        <View className='paddingHeight'></View>
        {/* 请选择帖子类型 */}
        <AtActionSheet
          isOpened={showModel}
          onClose={() => this.setState({showModel: false})}
          onCancel={() => this.setState({showModel: false})}
        >
          <View className="titleBox">
            <View></View>
            <Text className="title">请选择帖子类型</Text>
            <Image onClick={() => this.setState({showModel: false})} className="close" src={close} mode="widthFix" />
          </View>

          <ScrollView scrollY className="list">
            {tabList.length > 0 &&
              tabList.map((item) => (
                <>
                  <View
                    onClick={() => {
                      this.setState({showModel: false, titleId: item.id, titleName: item.name});
                    }}
                    className={titleId == item.id ? 'community-name-a' : 'community-name'}
                  >
                    {item.name}
                  </View>
                </>
              ))}
          </ScrollView>
        </AtActionSheet>
        <View className="bottom">
          <View className="btn_box">
            <Text
              className="btn-release"
              onClick={() => {
                this.submitPost();
              }}
            >
              发布
            </Text>
          </View>
        </View>
      </ScrollView>
    );
  }
}
